package cn.backflow.admin.service;

import cn.backflow.admin.Constants;
import cn.backflow.admin.entity.Dict;
import cn.backflow.admin.repository.DictRepository;
import cn.backflow.data.service.AbstractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@CacheConfig(cacheNames = Constants.SYSTEM_CACHE)
public class DictService extends AbstractService<Dict, Integer> {

    private DictRepository dictRepo;

    @Autowired
    public DictService(DictRepository dictRepo) {
        this.dictRepo = dictRepo;
    }

    @Cacheable(key = "'dict_' + #code")
    public Map<Comparable, Dict> findMapByCode(String code) {
        return dictRepo.findMapByCode(code, "code");
    }

    public List<Dict> findByCode(String code) {
        return dictRepo.findByCode(code);
    }

    @Override
    @Transactional
    @CacheEvict(key = "'dict_' + #dict.code")
    public int save(Dict dict) throws DataAccessException {
        return super.save(dict);
    }

    @Override
    @Transactional
    @CacheEvict(key = "'dict_' + #dict.code")
    public int update(Dict dict) throws DataAccessException {
        dictRepo.deleteByCode(dict.getCode());
        return super.update(dict);
    }

    @Override
    @Transactional
    @CacheEvict(key = "'dict_' + #dict.code")
    public int saveOrUpdate(Dict dict) {
        return dict.getId() == null ? save(dict) : update(dict);
    }

    @Transactional
    @CacheEvict(key = "'dict_' + #dicts[0].code")
    public int saveOrUpdate(List<Dict> dicts) {
        Dict parent = dicts.get(0);
        dictRepo.deleteByCode(parent.getCode());
        dictRepo.insert(parent);
        for (Dict dict : dicts) {
            dict.setParent(parent.getId());
        }
        return dictRepo.insertBatch(dicts);
    }

    @Transactional
    @CacheEvict(key = "'dict_' + #code")
    public int deleteByCode(String code) {
        return dictRepo.deleteByCode(code);
    }


}